package com.tang.multi.v2;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Tang
 * @classname SubReactor
 * @description [ 子 reactor ]
 * @date 2021/8/10 17:04
 */
@Slf4j
public class SubReactor implements Runnable {

    private Selector selector;

    @Getter
    private int id = 0;

    public SubReactor(Selector selector, int id) {
        this.id = id;
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            selector.select();
            Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 业务处理
                dispatch(selectionKey);
                iterator.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void dispatch(SelectionKey selectionKey) {
        Runnable runnable = (Runnable) selectionKey.attachment();
        runnable.run();
    }
}